package com.bl.base.http

import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

open class HttpCreater private constructor() {

    val timeOut: Long = 60 //30秒超时
    val baseUrlInterceptor: BaseUrlInterceptor = BaseUrlInterceptor()
    var okhttpClient: OkHttpClient
    var downOkHttpClient: OkHttpClient

    var loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
            //打印retrofit日志
            Log.i("log_http", "retrofitBack = $message")
        }
    })

    init {
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        okhttpClient = OkHttpClient.Builder()
            .connectTimeout(timeOut, TimeUnit.SECONDS)
            .readTimeout(timeOut, TimeUnit.SECONDS)
            .writeTimeout(timeOut, TimeUnit.SECONDS)
            .addInterceptor(baseUrlInterceptor)
            .addInterceptor(loggingInterceptor)
            .build()

        downOkHttpClient = OkHttpClient.Builder()
            .connectTimeout(timeOut, TimeUnit.SECONDS)
            .readTimeout(timeOut, TimeUnit.SECONDS)
            .writeTimeout(timeOut, TimeUnit.SECONDS)
            .build()
    }


    companion object {
        open val instance by lazy (LazyThreadSafetyMode.SYNCHRONIZED){
            HttpCreater()
        }
    }

    /**
     * 设置baseUrl 对应的token
     */
    open fun setToken(baseUrl: String,token:String){
        baseUrlInterceptor.setToken(baseUrl,token)
    }

    /**
     * 获取请求的retrofit
     */
    open fun getRetrofit(baseUrl:String) : Retrofit{
        val gson: Gson = GsonBuilder().setLenient().create();
       return  Retrofit.Builder()
            .client(okhttpClient)
            .baseUrl(baseUrl)
//            .addConverterFactory(GsonConverterFactory.create(gson)) //配置转化库 Gson解析失败，不报错崩溃
            .addConverterFactory(ScalarsConverterFactory.create()) //返回字符串
            .build()
    }


    /**
     * 下载的tokenretrofit
     */
    open fun getDownRetrofit(baseUrl:String) : Retrofit{
        return  Retrofit.Builder()
            .client(downOkHttpClient)
            .baseUrl(baseUrl)
            .addConverterFactory(ScalarsConverterFactory.create()) //配置转化库 Gson解析失败，不报错崩溃
            .build()
    }
}